<template>
  <div>
    <div class="header" :style="{ backgroundColor: getHeaderBackgroundColor() }">
      <van-icon name="arrow-left" size="20px" @click="goBack" style="margin-top: -191px" />
      <div class="header-content">
        <h2 style="font-size: 50px; color: white;width: 288px;
    margin-left: 57px;">{{systolicPressure}} / {{diastolicPressure}} <span style="font-size: 20px">mmHg</span></h2>
        <p style="color: white">状态 {{getStatus()}}</p>
        <button @click="showBloodPressureModal = true" style="width: 147px; height: 50px; background-color: #FDDB78; border-radius: 40px; border: none; color: white; font-weight: 900">记录血压</button>
      </div>
      <div class="current-time" style="color: white">{{currentTime}}</div>
    </div>
    <!-- 外部盒子 -->
    <div class="chart-box">
      <h2>血压趋势 <span style="font-size:14px;color:gray">(单位：mmHg)</span></h2>
      <div class="chart-container">
        <canvas id="bloodPressureChart" width="400" height="250"></canvas>
      </div>
    </div>
    <div style="font-size: 23px;
    height: 45px;
    margin-left: 32px;">血压记录</div>
    <ul class="blood-pressure-records-list">
      <li v-for="(record, index) in bloodPressureRecords" :key="index" class="blood-pressure-record-item">
        <div class="record-date">{{formatDate(record.recordTime)}}</div>
        <div class="bp-value-wrapper">
          <div class="bp-value">{{record.systolicPressure}}/{{record.diastolicPressure}}</div>
          <div class="bp-unit">mmHg</div>
        </div>
        <span v-if="record.status === '正常'" class="status-normal">正常</span>
        <span v-if="record.status === '异常'" class="status-abnormal">异常</span>
        <div class="record-actions">
          <button @click="editRecord(index)" class="edit-button"><van-icon name="edit" size="16px" /></button>
          <button @click="deleteRecord(index)" class="delete-button"><van-icon name="delete" size="16px" /></button>
        </div>
      </li>
    </ul>
    <!-- 弹出层组件 -->
    <div v-if="showBloodPressureModal" class="blood-pressure-modal">
      <div class="modal-content">
        <h5 class="modal-title">血压记录</h5>
        <div class="blood-pressure-value-container">
          <h1 v-if="selectedType ==='systolic'">{{systolicValue}} mmHg</h1>
          <h1 v-if="selectedType === 'diastolic'">{{diastolicValue}} mmHg</h1>
        </div>
        <div class="toggle-buttons">
          <button :class="{ 'active': selectedType ==='systolic' }" @click="selectType('systolic')">收缩压</button>
          <button :class="{ 'active': selectedType === 'diastolic' }" @click="selectType('diastolic')">舒张压</button>
        </div>
        <div class="blood-pressure-slider-container">
          <!-- 添加min和max属性 -->
          <van-slider style="margin-left: 40px" v-model="selectedType ==='systolic'? systolicValue : diastolicValue" @change="onChange" min="20" max="200" />
        </div>
        <div class="button-group-container">
          <div class="button-group">
            <button @click="handleCancel" class="cancel-button">取消</button>
            <button @click="confirmBloodPressure" class="confirm-button">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart } from 'chart.js';
import { CategoryScale, LinearScale } from 'chart.js';
import { LineController } from 'chart.js';
import { PointElement, LineElement } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import axios from 'axios';
import { nextTick } from 'vue';


Chart.register(CategoryScale, LinearScale, LineController, PointElement, LineElement, ChartDataLabels);

export default {
  data() {
    return {
      systolicPressure: 120,
      diastolicPressure: 80,
      bloodPressureRecords: [
        // {
        //   id: 1,
        //   user_id: 1,
        //   systolic_pressure: 92,
        //   diastolic_pressure: 90,
        //   record_time: '2021-01-04 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 2,
        //   user_id: 1,
        //   systolic_pressure: 100,
        //   diastolic_pressure: 70,
        //   record_time: '2021-01-24 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 3,
        //   user_id: 1,
        //   systolic_pressure: 110,
        //   diastolic_pressure: 63,
        //   record_time: '2021-01-31 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 4,
        //   user_id: 1,
        //   systolic_pressure: 128,
        //   diastolic_pressure: 55,
        //   record_time: '2021-02-04 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 5,
        //   user_id: 1,
        //   systolic_pressure: 140,
        //   diastolic_pressure: 50,
        //   record_time: '2021-02-14 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 6,
        //   user_id: 1,
        //   systolic_pressure: 130,
        //   diastolic_pressure: 60,
        //   record_time: '2021-02-18 00:00:00',
        //   status: '正常'
        // },
        // {
        //   id: 7,
        //   user_id: 1,
        //   systolic_pressure: 90,
        //   diastolic_pressure: 90,
        //   record_time: '2021-03-01 00:00:00',
        //   status: '正常'
        // }
      ],
      chart: null,
      showBloodPressureModal: false,
      currentTime: '',
      recordData: {},
      isEdit: false,
      editRecordId: null,
      selectedValue: 120,
      selectedType:'systolic',
      systolicValue: 120, // 新增：用于存储收缩压拉动条数据
      diastolicValue: 80, // 新增：用于存储舒张压拉动条数据
    };
  },
  methods: {
    async fetchAllBloodPressureRecords() {
      try {
        const response = await axios.get('http://localhost:10086/api/user/user/fetchAllBloodPressureRecords');
        if (response.status === 200) {
          const records = response.data.data;
          // 遍历更新每条记录的状态
          records.forEach(record => {
            record.status = this.getStatus(record.systolicPressure, record.diastolicPressure);
            // 格式化日期
            record.recordTime = this.formatDate(record.recordTime);
          });
          this.bloodPressureRecords = records;
          await nextTick();
          this.drawChart();
        }
      } catch (error) {
        console.error('获取血压记录失败', error);
      }
    },
    editRecord(index) {
      const record = this.bloodPressureRecords[index];
      const { id, systolicPressure, diastolicPressure } = record;
      this.selectedType ='systolic';
      this.selectedValue = systolicPressure;
      this.systolicValue = systolicPressure; // 初始化收缩压变量
      this.diastolicValue = diastolicPressure; // 初始化舒张压变量
      this.editRecordId = id;
      this.isEdit = true;
      this.showBloodPressureModal = true;
    },
    deleteRecord(index) {
      const record = this.bloodPressureRecords[index];
      const { id } = record;
      axios.delete(`http://localhost:10086/api/doctor/health_monitoring_blood_pressure/deletePressureRecord/${id}`, {
        headers: {
          'token': JSON.parse(localStorage.getItem("token"))
        }
      })
          .then(response => {
            console.log('血压记录删除成功', response.data);
            console.log(`删除血压记录，id: ${id}`);
            this.bloodPressureRecords.splice(index, 1);
            this.drawChart();
          })
          .catch(error => {
            console.error('血压记录删除失败', error);
            this.$message.error('血压记录删除失败，请重试');
          });

    },
    findBloodPressure() {
      return Promise.resolve({ data: { data: this.bloodPressureRecords } });
    },
    selectType(type) {
      this.selectedType = type;
    },
    onChange(value) {
      if (this.selectedType ==='systolic') {
        this.systolicValue = value;
      } else {
        this.diastolicValue = value;
      }
      this.$toast(`当前 ${this.selectedType ==='systolic'? '收缩压' : '舒张压'} 值：${value}`);
      console.log(`当前 ${this.selectedType ==='systolic'? '收缩压' : '舒张压'} 值：${value}`);
    },
    goBack() {
      this.$router.go(-1);
    },
    drawChart() {
      const ctx = document.getElementById('bloodPressureChart').getContext('2d');
      const systolicDataPoints = this.bloodPressureRecords.map(record => record.systolicPressure);
      const diastolicDataPoints = this.bloodPressureRecords.map(record => record.diastolicPressure);
      const labels = this.bloodPressureRecords.map(record => record.recordTime);
      const today = this.formatDate(new Date());
      const systolicPointColors = [];
      const systolicBorderColors = [];
      const systolicDataLabelsColors = [];
      const diastolicPointColors = [];
      const diastolicBorderColors = [];
      const diastolicDataLabelsColors = [];

      for (let i = 0; i < systolicDataPoints.length; i++) {
        const recordDate = labels[i];
        if (recordDate === today) {
          systolicPointColors.push('white');
          systolicBorderColors.push('red');
          systolicDataLabelsColors.push('red');
          diastolicPointColors.push('white');
          diastolicBorderColors.push('red');
          diastolicDataLabelsColors.push('red');
        } else {
          systolicPointColors.push('white');
          systolicBorderColors.push('#00C853');
          systolicDataLabelsColors.push('#00C853');
          diastolicPointColors.push('white');
          diastolicBorderColors.push('#FFD600');
          diastolicDataLabelsColors.push('#FFD600');
        }
      }

      if (this.chart) {
        this.chart.destroy();
      }

      const minSystolic = Math.min(...systolicDataPoints);
      const maxSystolic = Math.max(...systolicDataPoints);
      const minDiastolic = Math.min(...diastolicDataPoints);
      const maxDiastolic = Math.max(...diastolicDataPoints);
      const yAxisMin = Math.floor(Math.min(minSystolic, minDiastolic) * 2) / 2 - 1;
      const yAxisMax = Math.ceil(Math.max(maxSystolic, maxDiastolic) * 2) / 2 + 1.5;

      this.chart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [
            {
              label: '收缩压 (单位：mmHg)',
              data: systolicDataPoints,
              borderColor: '#00C853',
              backgroundColor: 'rgba(0, 200, 83, 0.2)',
              pointRadius: 4,
              pointBackgroundColor: 'white',
              pointBorderColor: '#00C853',
              pointHoverRadius: 6,
              pointHoverBackgroundColor: 'white',
              pointHoverBorderColor: '#00C853',
              fill: 'origin',
              tension: 0.4
            },
            {
              label: '舒张压 (单位：mmHg)',
              data: diastolicDataPoints,
              borderColor: '#FFD600',
              backgroundColor: 'rgba(255, 214, 0, 0.2)',
              pointRadius: 4,
              pointBackgroundColor: 'white',
              pointBorderColor: '#FFD600',
              pointHoverRadius: 6,
              pointHoverBackgroundColor: 'white',
              pointHoverBorderColor: '#FFD600',
              fill: 'origin',
              tension: 0.4
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              type: 'category',
              grid: { display: false },
              ticks: { color: '#666', autoSkip: false, maxRotation: 0, padding: 5 },
              offset: true
            },
            y: {
              display: true,
              type: 'linear',
              beginAtZero: false,
              grid: {
                display: true,
                color: 'rgba(0, 0, 0, 0.08)',
                lineWidth: 1,
                drawBorder: false,
                zeroLineColor: 'rgba(0, 0, 0, 0.08)',
                zeroLineWidth: 1,
                gridLines: {
                  drawOnChartArea: true,
                  drawTicks: false,
                  min: yAxisMin,
                  max: yAxisMax,
                  stepSize: 5
                }
              },
              ticks: {
                display: false,
                min: yAxisMin,
                max: yAxisMax,
                stepSize: 5
              }
            }
          },
          plugins: {
            legend: { display: true },
            title: {
              display: true,
              text: '血压趋势 (单位：mmHg)',
              font: { size: 16, weight: 'bold', color: '#333' },
              padding: { bottom: 10 }
            },
            tooltip: { enabled: true },
            datalabels: {
              anchor: 'end',
              align: 'top',
              color: function (context) {
                return context.dataset.borderColor;
              },
              font: { size: 12, weight: 'bold' },
              formatter: (value) => `${value} mmHg`,
              display: 'auto',
              offset: 8,
              clamp: true,
              borderWidth: 0,
              borderRadius: 3
            }
          },
          layout: {
            padding: { left: 20, right: 20, top: 30, bottom: 10 }
          },
          elements: {
            line: {
              borderWidth: 2,
              tension: 0.4
            }
          }
        }
      });
    },
    confirmBloodPressure() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      const second = String(now.getSeconds()).padStart(2, '0');
      const systolic = typeof this.systolicValue === 'number'? this.systolicValue : parseFloat(this.systolicValue);
      const diastolic = typeof this.diastolicValue === 'number'? this.diastolicValue : parseFloat(this.diastolicValue);
      const minSystolic = 20;
      const maxSystolic = 200;
      const minDiastolic = 20;
      const maxDiastolic = 200;

      // 检查收缩压和舒张压是否在有效范围内
      if (systolic < minSystolic || systolic > maxSystolic) {
        this.$message.error('收缩压值不在有效范围内');
        return;
      }
      if (diastolic < minDiastolic || diastolic > maxDiastolic) {
        this.$message.error('舒张压值不在有效范围内');
        return;
      }

      const status = this.getStatus(systolic, diastolic);
      this.recordData = {
        // userId: 1, // 这里假设userId需要从其他地方获取，暂时注释
        systolicPressure: systolic,
        diastolicPressure: diastolic,
        // 修改recordTime的格式为符合需求的格式，这里假设后端接受的是 'YYYY-MM-DD HH:MM:SS'
        recordTime: new Date(),
        status: status
      };

      if (this.isEdit && this.editRecordId) {
        this.recordData.id = this.editRecordId;
        axios.post('http://localhost:10086/api/doctor/health_monitoring_blood_pressure/updatePressureRecord', this.recordData, {
          headers: {
            // 'Content-Type': 'application/json', // 如果后端需要特定的Content-Type，这里可以取消注释
            'token': JSON.parse(localStorage.getItem("token"))
          }
        })
            .then(response => {
              console.log('血压记录修改成功', response.data);
              // 这里可以添加提示用户修改成功的消息
              this.$message.success('血压记录修改成功');
              this.drawChart();
              this.fetchAllBloodPressureRecords();
              this.showBloodPressureModal = false;
              this.isEdit = false;
              this.editRecordId = null;
            })
            .catch(error => {
              console.error('血压记录修改失败', error);
              this.$message.error('血压记录修改失败，请重试');
            });
      } else {
        axios.post('http://localhost:10086/api/doctor/health_monitoring_blood_pressure/savePressureRecord', this.recordData, {
          headers: {
            'Content-Type': 'application/json',
            'token': JSON.parse(localStorage.getItem("token"))
          }
        })
            .then(response => {
              console.log('血压记录保存成功', response.data);
              // 这里可以添加提示用户保存成功的消息
              this.$message.success('血压记录保存成功');
              this.bloodPressureRecords.push(this.recordData);
              this.drawChart();
              this.fetchAllBloodPressureRecords();
              this.showBloodPressureModal = false;
            })
            .catch(error => {
              console.error('血压记录保存失败', error);
              this.$message.error('血压记录保存失败，请重试');
            });
      }
    },
    handleCancel() {
      this.showBloodPressureModal = false;
      this.selectedValue = this.selectedType ==='systolic'? this.systolicPressure : this.diastolicPressure;
    },
    getHeaderBackgroundColor() {
      return '#4A94F5';
    },
    updateCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      this.currentTime = `${year}-${month}-${day} ${hour}:${minute}`;
    },
    formatDate(date) {
      const d = new Date(date);
      const month = d.getMonth() + 1;
      const day = d.getDate();
      return `${month}/${day}`;
    },
    getStatus(systolic, diastolic) {
      const systolicInRange = systolic >= 90 && systolic < 140;
      const diastolicInRange = diastolic >= 60 && diastolic < 90;
      if (systolicInRange && diastolicInRange) {
        return '正常';
      }
      return '异常';
    },
  },
  mounted() {
    const status = this.getStatus(this.systolicPressure, this.diastolicPressure);
    // 这里如果有地方显示状态，可以更新状态显示
    this.drawChart();
    this.updateCurrentTime();
    setInterval(() => {
      this.updateCurrentTime();
    }, 60 * 1000);
  },
  async created() {
    await this.findBloodPressure();
    this.fetchAllBloodPressureRecords();
  }
};
</script>

<style scoped>
.header {
  position: relative;
  /* 使用线性渐变，从#35CD9E向浅色渐变 */
  background: linear-gradient(to bottom, #35CD9E, #6ae0c0);
  padding: 20px;
  text-align: center;
  background-size: cover;
  background-position: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-bottom-left-radius: 15px;
  border-bottom-right-radius: 15px;
  color: white;
  margin-top: 0; /* 确保顶部外边距为 0 */
}

.header-content {
  margin-right: 120px;
  margin-top: 20px;
  flex-direction: column;
  align-items: center;
}

.current-time {
  position: absolute;
  margin-right: 145px;
  margin-top: 20px;
  top: 10px;
  right: 10px;
  font-size: 14px;
}
.chart-box {
  border: 1px solid #ccc;
  border-radius: 15px;
  padding: 10px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 20px auto;
  width: 340px;
}

.chart-container {
  width: 100%;
  height: 250px;
}

.blood-pressure-records-list {
  list-style: none;
  padding: 0;
}

.blood-pressure-record-item {
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 0px 10px rgba(0, 112, 255, 0.5);
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 35px;
  width: 76%;
}
.bp-value-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.bp-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.bp-unit {
  font-size: 14px;
  color: #666;
}

.record-date {
  color: #666;
  font-size: 14px;
}

.record-systolic,
.record-diastolic {
  font-size: 18px;
  font-weight: bold;
}

.status-normal {
  background-color: #c8e6c9;
  color: #00CB85;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
}

.status-abnormal {
  background-color: #ef9a9a;
  color: #e53935;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 12px;
}

.record-actions {
  display: flex;
  align-items: center;
}

.edit-button,
.delete-button {
  background: none;
  border: none;
  margin-left: 10px;
  cursor: pointer;
}

.blood-pressure-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 300px;
  background-color: white;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
  animation: slide-up 0.3s ease;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modal-content {
  width: 100%;
  padding: 20px;
  text-align: center;
}

.modal-title {
  margin: 0;
  margin-bottom: 10px;
  text-align: center;
}

.blood-pressure-value-container {
  width: 100%;
  text-align: center;
}

.toggle-buttons {
  width: 240px;
  margin-left: 95px;
  background-color: #F2F2F2;
  border-radius: 5px;
  display: flex;
  justify-content: center; /* 添加此行，使内部元素水平居中 */
  margin-bottom: 40px;
}

.toggle-buttons button {
  padding: 5px 30px;
  border: none;
  border-radius: 5px;
  margin: 5px 5px;
  cursor: pointer;
}

.toggle-buttons button.active {
  border-radius: 5px;
  background-color: white;
  color: #81B8FC;
}

.blood-pressure-slider-container {
  width: 80%;
  margin-bottom: 20px;
}

.button-group-container {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
  box-sizing: border-box;
}

.button-group {
  display: flex;
}

.cancel-button {
  padding: 10px 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: white;
  color: #007AFF;
  font-weight: bold;
  margin-right: 10px;
}

.confirm-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007AFF;
  color: white;
  font-weight: bold;
}
</style>